﻿using Guoc.BigMall.Infrastructure.Log;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Guoc.BigMall.Infrastructure.Payment.AliPay
{
    public class AliPayGetway : IAliPayGetway
    {
        AliPayConfig _config;
        public AliPayGetway(AliPayConfig config)
        {
            _config = config;
        }

        //private Config GetConfig()
        //{
        //    return new Config()
        //    {
        //        Protocol = "https",
        //        GatewayHost = "openapi.alipay.com",
        //        SignType = "RSA2",

        //        AppId = "<-- 请填写您的AppId，例如：2019091767145019 -->",

        //        // 为避免私钥随源码泄露，推荐从文件中读取私钥字符串而不是写入源码中
        //        MerchantPrivateKey = "<-- 请填写您的应用私钥，例如：MIIEvQIBADANB ... ... -->",

        //        MerchantCertPath = "<-- 请填写您的应用公钥证书文件路径，例如：/foo/appCertPublicKey_2019051064521003.crt -->",
        //        AlipayCertPath = "<-- 请填写您的支付宝公钥证书文件路径，例如：/foo/alipayCertPublicKey_RSA2.crt -->",
        //        AlipayRootCertPath = "<-- 请填写您的支付宝根证书文件路径，例如：/foo/alipayRootCert.crt -->",

        //        // 如果采用非证书模式，则无需赋值上面的三个证书路径，改为赋值如下的支付宝公钥字符串即可
        //        // AlipayPublicKey = "<-- 请填写您的支付宝公钥，例如：MIIBIjANBg... -->"

        //        //可设置异步通知接收服务地址（可选）
        //        NotifyUrl = "<-- 请填写您的支付类接口异步通知接收服务地址，例如：https://www.test.com/callback -->",

        //        //可设置AES密钥，调用AES加解密相关接口时需要（可选）
        //        EncryptKey = "<-- 请填写您的AES密钥，例如：aa4BtZ4tspm2wnXLb1ThQA== -->"
        //    };
        //}

        public string StoreCode { get { return _config.StoreCode ; } }
        /// <summary>
        ///  统一转账
        ///  <para>out_biz_no  商户端的唯一订单号</para>
        ///  <para>trans_amount  订单总金额，单位为元，精确到小数点后两位，</para>
        ///  <para>product_code  单笔无密转账到支付宝账户固定为: TRANS_ACCOUNT_NO_PWD；</para>
        ///  <para>out_biz_no  商户端的唯一订单号</para>
        ///  <para>out_biz_no  商户端的唯一订单号</para>
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public AliPayResult UnifiedTransfer(AliPayRequest request)
        {
           var _log=  AppContext.Current.Resolve<ILogger>();
            // 附加请求公共参数
            AliPayRequest data = new AliPayRequest();
            data.Add("app_id", _config.AppId);
            data.Add("method", "alipay.fund.trans.uni.transfer");
            data.Add("charset", data.Charset);
            data.Add("sign_type", "RSA2");  // RSA2 或 RSA
            data.Add("timestamp", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            data.Add("version", "1.0");          
            data.Add("biz_content", request.SerializeObject());

            // 生成签名
            var privateKeyPath = Path.Combine(request.webRootPath, @"Alipay/5001.txt");
            var sign = AlipaySignature.RSASign(data.GetSignContent(), privateKeyPath, data.Charset, "RSA2");
            data.Add("sign", sign);

            var submitDataString= WebUtils.BuildQuery(data.Content, "utf-8");
            _log.Info("alipay uni.transafer request:{0}", submitDataString);
            WebUtils http = new WebUtils();
            var alipayUrl = @"https://openapi.alipay.com/gateway.do";
            var result= http.DoPost(alipayUrl, data.Content, data.Charset);
            _log.Info("alipay uni.transafer response:{0}", result);
            AliPayResult response = new AliPayResult();
            response= JsonConvert.DeserializeObject<AliPayResult>(result);

            return response;
        }
    }
}
